package com.quwancode.springbootmysql.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.quwancode.springbootmysql.common.page.PageResult;
import com.quwancode.springbootmysql.common.service.impl.BaseServiceImpl;
import com.quwancode.springbootmysql.dto.StudentCreateDto;
import com.quwancode.springbootmysql.dto.StudentUpdateDto;
import com.quwancode.springbootmysql.mapper.StudentMapper;
import com.quwancode.springbootmysql.model.Student;
import com.quwancode.springbootmysql.query.StudentQuery;
import com.quwancode.springbootmysql.service.StudentService;
import com.quwancode.springbootmysql.vo.StudentVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chuck
 * @since 2023-10-16
 */
@Service
public class StudentServiceImpl extends BaseServiceImpl<StudentMapper, Student> implements StudentService {

    private LambdaQueryWrapper<Student> getWrapper(StudentQuery query) {
        LambdaQueryWrapper<Student> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(StringUtils.isNotBlank(query.getSsex()), Student::getSsex, query.getSsex());
        return wrapper;
    }

    @Override
    public PageResult<StudentVo> page(StudentQuery query) {

        IPage<Student> page = page(getPage(query), getWrapper(query));

        // modelList -> voList
        ArrayList<StudentVo> voList = new ArrayList<>();
        for (Student model : page.getRecords()) {
            StudentVo vo = new StudentVo();
            BeanUtils.copyProperties(model, vo);
            voList.add(vo);
        }

        return new PageResult<>(voList, page.getTotal(), page.getSize(), page.getCurrent(), page.getPages());
    }

    @Override
    public StudentVo get(Long id) {
        Student model = getById(id);
        StudentVo vo = new StudentVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    @Override
    public void save(StudentCreateDto dto) {
        Student model = new Student();
        BeanUtils.copyProperties(dto, model);

        baseMapper.insert(model);
    }

    @Override
    public void update(StudentUpdateDto dto) {
        Student model = new Student();
        BeanUtils.copyProperties(dto, model);

        updateById(model);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        removeByIds(idList);
    }

}
